#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@file:installpro.py
@time:2017/7/13 0013 16:38
"""
from users.views import auth_user
from django.shortcuts import HttpResponse,render,redirect,reverse
from cmdb.models import hostInfo,hostGroup
from .models import element,deployTask,taskSchedu
import json
@auth_user
def system_install(request):
    allhosts = hostInfo.objects.all()
    allgroups = hostGroup.objects.all()
    allelements = element.objects.all()
    alltasks = deployTask.objects.all()
    allschedu = taskSchedu.objects.all()
    return render(request,'deploy-install.html',{
        'allhosts':allhosts,
        'allhostgroups':allgroups,
        'allelements':allelements,
        'alltasks':alltasks,
        'allschedu':allschedu,
    })

@auth_user
def add_element(request):
    element_name = request.POST.get('element_name',None)
    element_humaname = request.POST.get('element_humaname',None)
    element_desc = request.POST.get('element_desc',None)
    element.objects.create(elementName=element_name,elementHumanName=element_humaname.lower(),elementDesc=element_desc)
    return HttpResponse('ok')
def del_element(request):
    pass

def add_task(request):
    taskname = request.POST.get('taskname')
    taskdesc = request.POST.get('taskdesc')
    deployTask.objects.create(taskName=taskname,taskDesc=taskdesc)
    return HttpResponse('ok')

def task_schedu(request):
    alldata  = request.POST.getlist('alldata[]')
    for a in alldata:
        data = json.loads(a)
        hostandgroup = data['hostandgroup']
        taskid = data['taskid']
        elementlists = data['elementlists']
        hostlist = []
        for b in hostandgroup.split(','):
            if b.startswith('h'):
                hostlist.append(int(b.lstrip('h')))
            elif b.startswith('g'):
                gid = b.lstrip('g')
                hostgroupobj = hostGroup.objects.get(id=gid)
                hosts = hostgroupobj.hostinfo_set.all()
                for h in hosts:
                    hostlist.append(h.id)
        hostportlsit = []
        for hid in set(hostlist):
            hostobj = hostInfo.objects.get(id=hid)
            hostname = hostobj.hostName
            hostip = hostobj.hostPublicIP
            hostport = hostobj.hostSSHPort
            hostiport = hostip + ':'+str(hostport)
            hostportlsit.append(hostiport)
        taskSchedu.objects.create(taskname_id=int(taskid),hostiport= ','.join(hostportlsit),elementList=elementlists)
    return HttpResponse('ok')